package com.wuzhipeng.xuechengcontent.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wuzhipeng.xuechengbase.exception.XueChengPlusException;
import com.wuzhipeng.xuechengbase.model.PageParams;
import com.wuzhipeng.xuechengbase.model.PageResult;
import com.wuzhipeng.xuechengcontent.dao.CourseBase;
import com.wuzhipeng.xuechengcontent.dao.CourseCategory;
import com.wuzhipeng.xuechengcontent.dao.CourseMarket;
import com.wuzhipeng.xuechengcontent.dto.AddCourseDto;
import com.wuzhipeng.xuechengcontent.dto.CourseBaseInfoDto;
import com.wuzhipeng.xuechengcontent.dto.EditCourseDTO;
import com.wuzhipeng.xuechengcontent.dto.QueryCourseParamsDto;
import com.wuzhipeng.xuechengcontent.mapper.CourseBaseMapper;
import com.wuzhipeng.xuechengcontent.mapper.CourseCategoryMapper;
import com.wuzhipeng.xuechengcontent.mapper.CourseMarketMapper;
import com.wuzhipeng.xuechengcontent.service.ICourseBaseService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author wuzhiheng
 * @since 2025-03-18
 */
@Service
@RequiredArgsConstructor
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements ICourseBaseService {
    /**
     * 课程基本信息Mapper
     */
    private final CourseBaseMapper courseBaseMapper;
    /**
     *  课程营销信息Mapper
     */
    private final CourseMarketMapper courseMarketMapper;
    /**
     * 课程分类Mapper
     */
    private final CourseCategoryMapper courseCategoryMapper;
    /**
     * @description 条件查询课程
     * @param pageParams 分页参数
     * @param queryCourseParamsDto 条件条件
     * @return PageResult 分页结果
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //构建查询条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件，根据课程名称查询
        if(!ObjectUtil.isEmpty(queryCourseParamsDto)) {
            queryWrapper.like(StrUtil.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
            //构建查询条件，根据课程审核状态查询
            queryWrapper.eq(StrUtil.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
            //构建查询条件，根据课程发布状态查询
            queryWrapper.eq(StrUtil.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());
        }
        PageHelper.startPage(pageParams.getPageNo().intValue(), pageParams.getPageSize().intValue());
        // 查询数据内容获得结果
        Page<CourseBase> pageResult = (Page<CourseBase>)baseMapper.selectList(queryWrapper);
        // 获取数据列表
        List<CourseBase> list = pageResult.getResult();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        com.wuzhipeng.xuechengbase.model.PageResult<CourseBase> courseBasePageResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        // 返回结果集
        return courseBasePageResult;
    }
    /**
     * @description 新增课程基本信息及课程营销信息
     * @param companyId 机构id
     * @param dto 课程基本信息及营销信息
     * @return CourseBaseInfoDto 课程基本信息及营销信息
     */
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {

        //合法性校验
        if (StrUtil.isBlank(dto.getName())) {
            throw new RuntimeException("课程名称为空");
        }

        if (StrUtil.isBlank(dto.getMt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StrUtil.isBlank(dto.getSt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StrUtil.isBlank(dto.getGrade())) {
            throw new RuntimeException("课程等级为空");
        }

        if (StrUtil.isBlank(dto.getTeachmode())) {
            throw new RuntimeException("教育模式为空");
        }

        if (StrUtil.isBlank(dto.getUsers())) {
            throw new RuntimeException("适应人群为空");
        }

        if (StrUtil.isBlank(dto.getCharge())) {
            throw new RuntimeException("收费规则为空");
        }
        //新增对象
        CourseBase courseBaseNew = new CourseBase();
        //将填写的课程信息赋值给新增对象
        BeanUtils.copyProperties(dto,courseBaseNew);
        //设置审核状态
        courseBaseNew.setAuditStatus("202002");
        //设置发布状态
        courseBaseNew.setStatus("203001");
        //机构id
        courseBaseNew.setCompanyId(companyId);
        //添加时间
        courseBaseNew.setCreateDate(LocalDateTime.now());
        //插入课程基本信息表
        int insert = courseBaseMapper.insert(courseBaseNew);
        if(insert<=0){
            throw new RuntimeException("新增课程基本信息失败");
        }
        //向课程营销表保存课程营销信息
        //课程营销信息
        CourseMarket courseMarketNew = new CourseMarket();
        Long courseId = courseBaseNew.getId();
        BeanUtils.copyProperties(dto,courseMarketNew);
        courseMarketNew.setId(courseId);
        int i = saveCourseMarket(courseMarketNew);
        if(i<=0){
            throw new RuntimeException("保存课程营销信息失败");
        }
        //查询课程基本信息及营销信息并返回
        return getCourseBaseInfo(courseId);

    }
    /**
     * @description 保存课程营销信息
     * @param courseMarketNew 课程营销信息
     * @return int 影响行数
     */
    private int saveCourseMarket(CourseMarket courseMarketNew){
        //收费规则
        String charge = courseMarketNew.getCharge();
        if(StrUtil.isBlank(charge)){
            throw new RuntimeException("收费规则没有选择");
        }
        //收费规则为收费
        if("201001".equals(charge)){
            if(courseMarketNew.getPrice() == null || courseMarketNew.getPrice() <=0){
                throw new RuntimeException("课程为收费价格不能为空且必须大于0");
            }
        }
        //根据id从课程营销表查询
        CourseMarket courseMarketObj = courseMarketMapper.selectById(courseMarketNew.getId());
        if(courseMarketObj == null){
            return courseMarketMapper.insert(courseMarketNew);
        }else{
            BeanUtils.copyProperties(courseMarketNew,courseMarketObj);
            courseMarketObj.setId(courseMarketNew.getId());
            return courseMarketMapper.updateById(courseMarketObj);
        }
    }
    /**
     * @description 根据课程id查询课程基本信息及营销信息
     * @param courseId 课程id
     * @return CourseBaseInfoDto 课程基本信息及营销信息
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){

        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //查询分类名称
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());

        return courseBaseInfoDto;

    }

    /**
     * @description 修改课程基本信息及课程营销信息
     * @param companyId 机构id
     * @param dto 课程基本信息及营销信息
     * @return CourseBaseInfoDto 课程基本信息及营销信息s
     */
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDTO dto) {
        //课程id
        Long courseId = dto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase==null){
            XueChengPlusException.cast("课程不存在");
        }

        //校验本机构只能修改本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }

        //封装基本信息的数据
        BeanUtils.copyProperties(dto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());

        //更新课程基本信息
        int i = courseBaseMapper.updateById(courseBase);

        //封装营销信息的数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto,courseMarket);
        saveCourseMarket(courseMarket);
        //查询课程信息
        CourseBaseInfoDto courseBaseInfo = this.getCourseBaseInfo(courseId);
        return courseBaseInfo;

    }


}
